/**
 * 
 */
package org.cnbi.utils.db;
/**
 * Copyright © 2014中国经邦. All rights reserved.
 * 
 * @author 龚佳新
 * @date 2014年4月25日下午1:57:53
 * @cnbi-utils
 */
public final class SQLServer2005Dialect {
	public SQLServer2005Dialect() {
	}

	public static String getLimitString(String sql,int currentPage, int pageSize) {
		String[] querySelects = getQuerySelects(sql);
		int startIndex = (currentPage-1)*pageSize;
		StringBuffer result = new StringBuffer(sql.length() + 100);
		result.append("select * from(");
		result.append(querySelects[0]);
		result.append(",row_number()over(");
		result.append(querySelects[2]);
		result.append(") as row");
		result.append(querySelects[1]);
		result.append(") tmp where tmp.row between ");
		result.append(startIndex + 1);
		result.append(" and ");
		result.append(pageSize*currentPage);
		return result.toString();
	}

	// 通过sql语句，得到相应的select、from and where、order by三条语句
	private static String[] getQuerySelects(String querySelect) {
		String[] result = new String[3];
		if (querySelect.indexOf(" from ") == -1 || querySelect.indexOf(" order by ") == -1) {
			throw new RuntimeException("不支持不带from和order by的分页查询语句");
		}
		String select = querySelect.substring(0, querySelect.indexOf(" from "));
		// while (select.endsWith(" ")) {
		// select.substring(0, select.length() - 1);
		// }
		result[0] = select;
		result[1] = querySelect.substring(querySelect.indexOf(" from "), querySelect.indexOf(" order by "));
		result[2] = querySelect.substring(querySelect.indexOf(" order by "));
		return result;
	}

	public boolean supportsLimitOffset() {
		return true;
	}
   public static void main(String[] args) {
	   SQLServer2005Dialect bean = new SQLServer2005Dialect();
	   String sql = bean.getLimitString("select * from Sys_Logs order by nid",1,10);
	   System.out.println("sql=="+sql);
}
}
